package junit.framework;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * A <code>TestFailure</code> collects a failed test together with
 * the caught exception.
 *
 * <code>TestFailure</code> 收集了 测试失败的信息，而不是抛出一个异常。
 * 关于 <code>Failure</code> 和 <code>Error</code>的区别 可以查看 {@link TestResult}的注释
 * @see TestResult
 */
public class TestFailure {
	/**
	 * 失败的测试
	 */
	protected Test fFailedTest;
	/**
	 * 失败的测试的异常信息
	 */
	protected Throwable fThrownException;
	
	/**
	 * Constructs a TestFailure with the given test and exception.
	 */
	public TestFailure(Test failedTest, Throwable thrownException) {
		fFailedTest= failedTest;
		fThrownException= thrownException;
	}
	/**
	 * Gets the failed test.
	 */
	public Test failedTest() {
	    return fFailedTest;
	}
	/**
	 * Gets the thrown exception.
	 */
	public Throwable thrownException() {
	    return fThrownException;
	}
	/**
	 * Returns a short description of the failure.
	 * StringBuilder 在jdk 8之后，就不需要了，因为jvm在底层实现了StringBuilder
	 */
	public String toString() {
		return String.valueOf(fFailedTest) + ": " + fThrownException.getMessage();
	}

	/**
	 * 获得异常的堆栈踪迹
	 */
	public String trace() {
		StringWriter stringWriter= new StringWriter();
		PrintWriter writer= new PrintWriter(stringWriter);
		thrownException().printStackTrace(writer);
		StringBuffer buffer= stringWriter.getBuffer();
		return buffer.toString();
	}
	public String exceptionMessage() {
		return thrownException().getMessage();
	}
	public boolean isFailure() {
		return thrownException() instanceof AssertionFailedError;
	}
}